package com.dudu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dudu.dto.OrderUserDto;
import com.dudu.dto.ResultDto;
import com.dudu.mapper.OrderMapper;
import com.dudu.pojo.Orders;
import com.dudu.pojo.Services;
import com.dudu.prop.WeiPayProperties;
import com.dudu.service.OrderService;
import com.dudu.utils.HttpClient;
import com.dudu.vo.ConfirmPhoneVo;
import com.github.wxpay.sdk.WXPayUtil;
import org.junit.jupiter.api.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WeiPayProperties weiPayProperties;

    @Override
    public ResultDto addOrder(Orders orders) {

        orders.setOutTradeNo(WeiPayServiceImpl.generateOrderNumber());
        int insert = orderMapper.insert(orders);

        if (insert > 0) {
            return ResultDto.success("订单插入数据库成功", orders);
        } else {
            return ResultDto.error("订单插入数据库失败", null);
        }

    }

    @Override
    public List<OrderUserDto> getOrderList() {
        List<OrderUserDto> ordersList = orderMapper.getOrdersList();
        List<OrderUserDto> newOrderList = new ArrayList<>();
        for (OrderUserDto orderUserDto : ordersList) {
            Services services = orderMapper.getServiceByOrderId(orderUserDto.getOrderId());
            if (services == null) {
                newOrderList.add(orderUserDto);
            }
        }
        return newOrderList;
    }

    @Override
    public boolean receiveOrder(Services services) {
        return orderMapper.receiveOrder(services);
    }

    @Override
    public ResultDto confirmPhone(ConfirmPhoneVo confirmPhoneVo) {
        Services services = orderMapper.confirmPhone(confirmPhoneVo);
        if (services == null) {
            return ResultDto.error("手机尾号错误！", null);
        }
        return ResultDto.success("手机尾号确认成功！", null);
    }

    @Override
    public ResultDto getOrderById(Orders orders) {
        Orders order = orderMapper.getOrderById(orders);
        return ResultDto.success("获取成功!", order);
    }

    @Override
    public ResultDto updateOrderStatus(Orders orders) {
        boolean result = orderMapper.updateOrderStatus(orders);
        if (result) {
            return ResultDto.success("取消订单成功", null);
        } else {
            return ResultDto.error("取消订单失败", null);
        }
    }

    @Override
    public ResultDto tui(String orderId) {
        System.out.println(orderId + "90");

        try {
            long num = Long.parseLong(orderId); // 尝试将字符串转换为long
            System.out.println(num); // 输出数值，没有引号
        } catch (NumberFormatException e) {
            System.out.println("数值超出范围");
        }
        Orders orderInfo = orderMapper.getOrderByOrderId(orderId);
        System.out.println(orderInfo);
        if (orderInfo == null) {
            return ResultDto.error("订单不存在", null);
        } else {
            //执行微信退款
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");

            Map<String, String> paramMap = new HashMap<>(8);

            paramMap.put("appid", weiPayProperties.getAppid());       //公众账号ID
            paramMap.put("mch_id", weiPayProperties.getPartner());   //商户编号
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            paramMap.put("transaction_id", orderInfo.getTransactionId()); //微信支付订单号

            paramMap.put("out_trade_no", orderInfo.getOutTradeNo()); //商户订单编号
            paramMap.put("out_refund_no", "tk" + orderInfo.getOutTradeNo()); //商户退款单号
            //       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            //       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");

            paramMap.put("total_fee", "1");
            paramMap.put("refund_fee", "1");
            try {
                String paramXml = WXPayUtil.generateSignedXml(paramMap, weiPayProperties.getPartnerkey());
                httpClient.setXmlParam(paramXml);
                httpClient.setHttps(true);
                httpClient.setCert(true); //设置证书支持
                httpClient.setCertPassword(weiPayProperties.getPartner()); //设置证书密码
                httpClient.post();

                String content = httpClient.getContent();
                Map<String, String> resultMap = WXPayUtil.xmlToMap(content);
                if ("SUCCESS".equals(resultMap.get("result_code"))) { //微信退款成功
//                refundInfo.setTradeNo(resultMap.get("refund_id"));//微信退款交易号
//                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
//                refundInfo.setCallbackTime(new Date());
//                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
//                refundInfoService.updateById(refundInfo);
                    return ResultDto.success("退款成功", null);

                }
                return ResultDto.error("退款失败", null);

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return ResultDto.error("退款失败", null);
    }


}
